package main

import (
	"bytes"
	"encoding/binary"
	"encoding/json"
	"io"
)

type MessageSign uint8

const (
	_ MessageSign = iota
	SignClientSub
	SignClientPub
	SignComingMsg
)

func ReadPacket(conn io.Reader) (id uint32, msg Message, sign MessageSign, err error) {
	// 从连接读取头数据
	var (
		length uint32
	)
	//	binary.Read(conn, binary.BigEndian, &length)
	//	binary.Read(conn, binary.BigEndian, &sign)
	//	binary.Read(conn, binary.BigEndian, &id)

	buf := make([]byte, 9)
	_, err = conn.Read(buf)
	if err != nil {
		return
	}
	length = binary.BigEndian.Uint32(buf[0:4])
	sign = MessageSign(buf[4])
	id = binary.BigEndian.Uint32(buf[5:])

	// 按长度读取内容
	content := make([]byte, length)
	conn.Read(content)
	msg = Message{}
	json.Unmarshal(content, &msg)
	return id, msg, sign, nil
}

func WritePacket(conn io.Writer, id uint32, msg Message, sign MessageSign) {
	jsonBytes, _ := json.Marshal(msg)
	b := make([]byte, 0)
	buf := bytes.NewBuffer(b)
	binary.Write(buf, binary.BigEndian, uint32(len(jsonBytes)))
	binary.Write(buf, binary.BigEndian, uint8(sign))
	binary.Write(buf, binary.BigEndian, uint32(id))
	binary.Write(buf, binary.BigEndian, jsonBytes)
	//	fmt.Println(len(b), buf.Bytes())
	conn.Write(buf.Bytes())
}
